<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
import React, { useState, useEffect } from 'react';
<%_ if (paginationInfiniteScroll) { _%>
import InfiniteScroll from 'react-infinite-scroll-component';
<%_ } _%>
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { Button, <% if (searchEngineAny) { %>Input, InputGroup, FormGroup, Form, Row, Col, <% } %>Table } from 'reactstrap';
import {
<%_ if (anyFieldIsBlobDerived) { _%>
  <%_ if (anyFieldHasFileBasedContentType) { _%>
  openFile,
  <%_ } _%>
  byteSize,
<%_ } _%>
  Translate<% if (searchEngineAny) { %>, translate<% } %>
  <% if (anyFieldIsDateDerived) { %>, TextFormat<% } %>
<%_ if (paginationNo) { _%>
  , getSortState
<%_ } else { _%>
  , getPaginationState
  <%_ if (paginationPagination) { _%>
  , JhiPagination, JhiItemCount
  <%_ } _%>
<%_ } _%>
} from 'react-jhipster';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSort, faSortUp, faSortDown } from '@fortawesome/free-solid-svg-icons';
<%_ if (anyFieldIsInstant || anyFieldIsZonedDateTime || anyFieldIsLocalDate) { _%>
import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants';
<%_ } _%>
import { ASC, DESC<%_ if (!paginationNo) { _%>, ITEMS_PER_PAGE<%_ } _%>, SORT } from 'app/shared/util/pagination.constants';
<%_ if (paginationNo) { _%>
import { overrideSortStateWithQueryParams } from 'app/shared/util/entity-utils';
<%_ } else { _%>
import { overridePaginationStateWithQueryParams } from 'app/shared/util/entity-utils';
<%_ } _%>
import { useAppDispatch, useAppSelector } from 'app/config/store';
<%_ if (anyFieldIsDuration) { _%>
import { DurationFormat } from 'app/shared/DurationFormat';
<%_ } _%>

import {
<%_ if (searchEngineAny) { _%>
  searchEntities,
<%_ } _%>
  getEntities,
<%_ if (paginationInfiniteScroll) { _%>
  reset,
<%_ } _%>
} from './<%= entityFileName %>.reducer';

export const <%= entityReactName %> = () => {
  const dispatch = useAppDispatch();

  const pageLocation = useLocation();
<%_ if (!paginationInfiniteScroll) { _%>
  const navigate = useNavigate();
<%_ } _%>

<%_ if (searchEngineAny) { _%>
  const [search, setSearch] = useState('');
<%_ } _%>
<%_ if (paginationNo) { _%>
  const [sortState, setSortState] = useState(overrideSortStateWithQueryParams(getSortState(pageLocation, '<%= primaryKey.name %>'), pageLocation.search));
<%_ } else { _%>
  const [paginationState, setPaginationState] = useState(overridePaginationStateWithQueryParams(getPaginationState(pageLocation, ITEMS_PER_PAGE, '<%= primaryKey.name %>'), pageLocation.search));
<%_ } _%>
<%_ if (paginationInfiniteScroll) { _%>
  const [sorting, setSorting] = useState(false);
<%_ } _%>

  const <%= entityInstance %>List = useAppSelector(state => state.<%= entityReactState %>.entities);
  const loading = useAppSelector(state => state.<%= entityReactState %>.loading);
<%_ if (paginationPagination) { _%>
  const totalItems = useAppSelector(state => state.<%= entityReactState %>.totalItems);
<%_ } _%>
<%_ if (paginationInfiniteScroll) { _%>
  const links = useAppSelector(state => state.<%= entityReactState %>.links);
  const updateSuccess = useAppSelector(state => state.<%= entityReactState %>.updateSuccess);
<%_ } _%>

  const getAllEntities = () => {
<%_ if (searchEngineAny) { _%>
    if (search) {
      dispatch(
        searchEntities({
          query: search,
  <%_ if (paginationNo) { _%>
          sort: `${sortState.sort},${sortState.order}`
  <%_ } else { _%>
          page: paginationState.activePage - 1,
          size: paginationState.itemsPerPage,
          sort: `${paginationState.sort},${paginationState.order}`
  <%_ } _%>
        })
      );
    } else {
      dispatch(
        getEntities({
  <%_ if (paginationNo) { _%>
          sort: `${sortState.sort},${sortState.order}`,
  <%_ } else { _%>
          page: paginationState.activePage - 1,
          size: paginationState.itemsPerPage,
          sort: `${paginationState.sort},${paginationState.order}`,
  <%_ } _%>
        })
      );
    }
<%_ } else { _%>
      dispatch(
        getEntities({
  <%_ if (paginationNo) { _%>
          sort: `${sortState.sort},${sortState.order}`,
  <%_ } else { _%>
          page: paginationState.activePage - 1,
          size: paginationState.itemsPerPage,
          sort: `${paginationState.sort},${paginationState.order}`,
<%_ } _%>
        })
      );
<%_ } _%>
  };

<%_ if (paginationInfiniteScroll) { _%>
  const resetAll = () => {
    dispatch(reset());
    setPaginationState({
      ...paginationState,
      activePage: 1
    });
    dispatch(getEntities({}));
  };
<%_ } _%>

<%_ if (paginationInfiniteScroll) { _%>
  useEffect(() => {
    resetAll();
  }, []);
<%_ } _%>

<%_ if (searchEngineAny) { _%>
  const startSearching = (e) => {
    if (search) {
  <%_ if (paginationInfiniteScroll) { _%>
      dispatch(reset());
  <%_ } _%>
  <%_ if (paginationNo) { _%>
      dispatch(searchEntities({
        query: search,
        sort: `${sortState.sort},${sortState.order}`,
      }));
  <%_ } else { _%>
      setPaginationState({
        ...paginationState,
        activePage: 1
      });
      dispatch(
        searchEntities({
          query: search,
          page: paginationState.activePage - 1,
          size: paginationState.itemsPerPage,
          sort: `${paginationState.sort},${paginationState.order}`,
        })
      );
  <%_ } _%>
    }
    e.preventDefault();
  };

  const clear = () => {
  <%_ if (paginationInfiniteScroll) { _%>
    dispatch(reset());
  <%_ } _%>
    setSearch('');
  <%_ if (!paginationNo) { _%>
    setPaginationState({
      ...paginationState,
      activePage: 1
    });
  <%_ } _%>
    dispatch(getEntities({}));
  };

  const handleSearch = event => setSearch(event.target.value);
<%_ } _%>

<%_ if (paginationInfiniteScroll) { _%>
  useEffect(() => {
    if (updateSuccess) {
      resetAll();
    }
  }, [updateSuccess]);

  useEffect(() => {
    getAllEntities()
  }, [paginationState.activePage]);

  const handleLoadMore = () => {
    if ((window as any).pageYOffset > 0) {
      setPaginationState({
        ...paginationState,
        activePage: paginationState.activePage + 1
      });
    }
  };
<%_ } _%>

<%_ if (paginationNo || paginationPagination) { _%>
  const sortEntities = () => {
    getAllEntities();
  <%_ if (paginationNo) { _%>
    const endURL = `?sort=${sortState.sort},${sortState.order}`;
  <%_ } else { _%>
    const endURL = `?page=${paginationState.activePage}&sort=${paginationState.sort},${paginationState.order}`;
  <%_ } _%>
    if (pageLocation.search !== endURL) {
      navigate(`${pageLocation.pathname}${endURL}`);
    }
  };
<%_ } _%>

  useEffect(() => {
<%_ if (paginationInfiniteScroll) { _%>
    if (sorting) {
      getAllEntities();
      setSorting(false);
    }
<%_ } else { _%>
    sortEntities();
<%_ } _%>
  }, [<% if (paginationInfiniteScroll) { %>sorting<% } else if (paginationPagination) { %>paginationState.activePage, paginationState.order, paginationState.sort<% } else { %>sortState.order, sortState.sort<% } %><%_ if (searchEngineAny) { _%>, search<% } %>]);

<%_ if (paginationPagination) { _%>
  useEffect(() => {
    const params = new URLSearchParams(pageLocation.search);
    const page = params.get('page');
    const sort = params.get(SORT);
    if (page && sort) {
      const sortSplit = sort.split(',');
      setPaginationState({
        ...paginationState,
        activePage: +page,
        sort: sortSplit[0],
        order: sortSplit[1]
      });
    }
  }, [pageLocation.search]);
<%_ } _%>

  const sort = p => () => {
<%_ if (paginationInfiniteScroll) { _%>
    dispatch(reset());
    setPaginationState({
      ...paginationState,
      activePage: 1,
      order: paginationState.order === ASC ? DESC : ASC,
      sort: p
    });
    setSorting(true);
<%_ } else if (paginationPagination) { _%>
    setPaginationState({
      ...paginationState,
      order: paginationState.order === ASC ? DESC : ASC,
      sort: p
    });
<%_ } else { _%>
    setSortState({
      ...sortState,
      order: sortState.order === ASC ? DESC : ASC,
      sort: p
    });
<%_ } _%>
  };

<%_ if (paginationPagination) { _%>
  const handlePagination = currentPage =>
    setPaginationState({
      ...paginationState,
      activePage: currentPage
    });
<%_ } _%>

  const handleSyncList = () => {
<%_ if (paginationNo || paginationPagination) { _%>
      sortEntities();
<%_ } _%>
<%_ if (paginationInfiniteScroll) { _%>
      resetAll();
<%_ } _%>
  };

  const getSortIconByFieldName = (fieldName: string) => {
<%_ if (paginationNo) { _%>
    const sortFieldName = sortState.sort;
    const order = sortState.order;
<%_ } else { _%>
    const sortFieldName = paginationState.sort;
    const order = paginationState.order;
<%_ } _%>
    if (sortFieldName !== fieldName) {
      return faSort;
    } else {
      return (order === ASC) ? faSortUp : faSortDown;
    }
  };

  return (
    <div>
      <h2 id="<%= entityFileName %>-heading" data-cy="<%- entityNameCapitalized %>Heading">
        <Translate contentKey="<%= i18nKeyPrefix %>.home.title"><%= entityNamePluralHumanized %></Translate>
        <div className="d-flex justify-content-end">
          <Button className="me-2" color="info" onClick={handleSyncList} disabled={loading}>
            <FontAwesomeIcon icon="sync" spin={loading} /> <Translate contentKey="<%= i18nKeyPrefix %>.home.refreshListLabel">Refresh List</Translate>
          </Button>
<%_ if (!readOnly) { _%>
            <Link to="/<%= entityPage %>/new" className="btn btn-primary jh-create-entity" id="jh-create-entity" data-cy="entityCreateButton">
              <FontAwesomeIcon icon="plus" />&nbsp;
              <Translate contentKey="<%= i18nKeyPrefix %>.home.createLabel">
                Create new <%= entityNameHumanized %>
              </Translate>
            </Link>
<%_ } _%>
        </div>
      </h2>
<%_ if (searchEngineAny) { _%>
      <Row>
        <Col sm="12">
          <Form onSubmit={startSearching}>
            <FormGroup>
              <InputGroup>
                <Input type="text" name="search" defaultValue={search} onChange={handleSearch}
              placeholder=<% if (enableTranslation) { %>{translate('<%= i18nKeyPrefix %>.home.search')}<% } else { %>"Search"<% } %>/>
                <Button className="input-group-addon">
                  <FontAwesomeIcon icon="search" />
                </Button>
                <Button type="reset" className="input-group-addon" onClick={clear}>
                  <FontAwesomeIcon icon="trash" />
                </Button>
              </InputGroup>
            </FormGroup>
          </Form>
        </Col>
      </Row>
<%_ } _%>
      <div className="table-responsive">
<%_ if (paginationInfiniteScroll) { _%>
        <InfiniteScroll dataLength={<%= entityInstance %>List ? <%= entityInstance %>List.length : 0}
                        next={handleLoadMore}
                        hasMore={paginationState.activePage - 1 < links.next}
                        loader={<div className="loader">Loading ...</div>}>
<%_ } _%>
        {
          <%= entityInstance %>List?.length > 0 ?(
            <Table responsive>
              <thead>
                <tr>
<%_ for (field of fields) { _%>
                  <th className="hand" onClick={sort('<%= field.fieldName %>')} ><Translate contentKey="<%= `${i18nKeyPrefix}.${field.fieldName}` %>"><%= field.fieldNameHumanized %></Translate> <FontAwesomeIcon icon={getSortIconByFieldName('<%= field.fieldName %>')} /></th>
<%_ } _%>
<%_ for (relationship of relationships) { _%>
    <%_ if (relationship.persistableRelationship && (paginationNo || !relationship.collection)) { _%>
                  <th><Translate contentKey="<%= `${i18nKeyPrefix}.${relationship.relationshipName}` %>"><%= relationship.relationshipNameHumanized %></Translate> <FontAwesomeIcon icon="sort" /></th>
    <%_ } _%>
<%_ } _%>
                  <th />
                </tr>
              </thead>
              <tbody>
                {
                  <%= entityInstance %>List.map(<%= entityInstance %> => (
                  <tr key={`entity-${<%= entityInstance %>.<%= primaryKey.name %>}`} data-cy="entityTable">
                    <td>
                      <Button tag={Link} to={`/<%= entityPage %>/${<%= entityInstance %>.<%= primaryKey.name %>}`} color="link" size="sm">
                        {<%= entityInstance %>.<%= primaryKey.name %>}
                      </Button>
                    </td>
<%_ for (field of fields) {
  const fieldType = field.fieldType;
  const fieldName = field.fieldName;
  const fieldIsEnum = field.fieldIsEnum;
_%>
  <%_ if (fieldName !== primaryKey.name) { _%>
                    <td>
    <%_ if (field.fieldTypeBoolean) { _%>
                      {<%= entityInstance %>.<%= field.fieldName %> ? 'true' : 'false'}
    <%_ } else if (field.fieldTypeTimed) { _%>
                      {<%= entityInstance %>.<%= fieldName %> ? <TextFormat type="date" value={<%= entityInstance %>.<%= fieldName %>} format={APP_DATE_FORMAT} />: null}
    <%_ } else if (field.fieldTypeDuration) { _%>
                      {<%= entityInstance %>.<%= fieldName %> ? <DurationFormat value={<%= entityInstance %>.<%= fieldName %>} />: null}
    <%_ } else if (field.fieldTypeLocalDate) { _%>
                      {<%= entityInstance %>.<%= fieldName %> ? <TextFormat type="date" value={<%= entityInstance %>.<%= fieldName %>} format={APP_LOCAL_DATE_FORMAT} />: null}
    <%_ } else if (fieldIsEnum && enableTranslation) { _%>
                      <Translate contentKey={`<%= frontendAppName %>.<%= fieldType %>.${<%= entityInstance %>.<%= fieldName %>}`} />
    <%_ } else if (field.fieldTypeBinary) { _%>
      <%_
        // blobFields
        if (!field.blobContentTypeText) {
      _%>
                        {<%= entityInstance %>.<%= fieldName %> ? (
                          <div>
                            {<%= entityInstance %>.<%= fieldName %>ContentType ? (
                              <a onClick={openFile(<%= entityInstance %>.<%= fieldName %>ContentType, <%= entityInstance %>.<%= fieldName %>)}>
        <%_ if (field.blobContentTypeImage) { _%>
                                  <img src={`data:${<%= entityInstance %>.<%= fieldName %>ContentType};base64,${<%= entityInstance %>.<%= fieldName %>}`} style={{ maxHeight: '30px' }} />
        <%_ } else { _%>
                                  <Translate contentKey="entity.action.open">Open</Translate>
        <%_ } _%>
                                &nbsp;
                              </a>
                            ) : null}
                            <span>{<%= entityInstance %>.<%= fieldName %>ContentType}, {byteSize(<%= entityInstance %>.<%= fieldName %>)}</span>
                          </div>
                        ) : null}
      <%_ } else { _%>
                          {<%= entityInstance %>.<%= fieldName %>}
      <%_ } _%>
    <%_ } else { _%>
                      {<%= entityInstance %>.<%= fieldName %>}
    <%_ } _%>
                    </td>
  <%_ } _%>
<%_ } _%>
<%_ for (relationship of relationships) {
  const otherEntity = relationship.otherEntity;
  const relationshipFieldName = relationship.relationshipFieldName;
  const relationshipFieldNamePlural = relationship.relationshipFieldNamePlural;
  const otherEntityPkName = relationship.otherEntity.primaryKey && relationship.otherEntity.primaryKey.name || 'id';
  const otherEntityField = relationship.otherEntityField; _%>
  <%_ if (relationship.persistableRelationship && (paginationNo || !relationship.collection)) { _%>
                    <td>
    <%_ if (relationship.otherEntityUser) { _%>
      <%_ if (relationship.relationshipManyToMany) { _%>
                      {
                        (<%= entityInstance %>.<%= relationshipFieldNamePlural %>) ?
                            (<%= entityInstance %>.<%= relationshipFieldNamePlural %>.map((val, j) =>
                                <span key={j}>{val.<%= otherEntityField %>}{(j === <%= entityInstance %>.<%= relationshipFieldNamePlural %>.length - 1) ? '' : ', '}</span>
                            )
                        ) : null
                      }
      <%_ } else { _%>
                      {<%= entityInstance + "." + relationshipFieldName %> ? <%= entityInstance + "." + relationshipFieldName + "." + otherEntityField %> : ''}
      <%_ } _%>
    <%_ } else { _%>
      <%_ if (relationship.relationshipManyToMany) { _%>
                        {
                          (<%= entityInstance %>.<%= relationshipFieldNamePlural %>) ?
                              (<%= entityInstance %>.<%= relationshipFieldNamePlural %>.map((val, j) =>
                                  <span key={j}><Link to={`/<%= otherEntity.entityPage %>/${val.<%= otherEntity.primaryKey.name %>}`}>{val.<%= otherEntityField %>}</Link>{(j === <%= entityInstance %>.<%= relationshipFieldNamePlural %>.length - 1) ? '' : ', '}</span>
                              )
                          ) : null
                        }
      <%_ } else { _%>
                        {<%= entityInstance + "." + relationshipFieldName %> ?
                        <Link to={`/<%= otherEntity.entityPage %>/${<%= entityInstance + "." + relationshipFieldName + "." + otherEntityPkName + "}" %>`}>
                          {<%= entityInstance + "." + relationshipFieldName + "." + otherEntityField %>}
                        </Link> : ''}
      <%_ } _%>
    <%_ } _%>
                      </td>
  <%_ } _%>
<%_ } _%>
                      <td className="text-end">
                        <div className="btn-group flex-btn-group-container">
                          <Button tag={Link} to={`/<%= entityPage %>/${<%= entityInstance %>.<%= primaryKey.name %>}`} color="info" size="sm" data-cy="entityDetailsButton">
                            <FontAwesomeIcon icon="eye" /> <span className="d-none d-md-inline" ><Translate contentKey="entity.action.view">View</Translate></span>
                          </Button>
<%_ if (!readOnly) { _%>
                          <Button tag={Link} to={`/<%= entityPage %>/${<%= entityInstance %>.<%= primaryKey.name %>}/edit<%_ if (paginationPagination) { _%>?page=${paginationState.activePage}&sort=${paginationState.sort},${paginationState.order}<%_ } _%>`} color="primary" size="sm" data-cy="entityEditButton">
                            <FontAwesomeIcon icon="pencil-alt" /> <span className="d-none d-md-inline"><Translate contentKey="entity.action.edit">Edit</Translate></span>
                          </Button>
                          <Button onClick={() => <% if (entityInstance !== 'window' ) { %>window.<% } %>location.href=`/<%= entityPage %>/${<%= entityInstance %>.<%= primaryKey.name %>}/delete<%_ if (paginationPagination) { _%>?page=${paginationState.activePage}&sort=${paginationState.sort},${paginationState.order}<%_ } _%>`} color="danger" size="sm" data-cy="entityDeleteButton">
                            <FontAwesomeIcon icon="trash" /> <span className="d-none d-md-inline"><Translate contentKey="entity.action.delete">Delete</Translate></span>
                          </Button>
<%_ } _%>
                        </div>
                      </td>
                    </tr>
                  ))
                }
              </tbody>
            </Table>
          ) : (
              !loading && <div className="alert alert-warning">
              <Translate contentKey="<%= i18nKeyPrefix %>.home.notFound">
                No <%= entityNamePluralHumanized %> found
              </Translate>
            </div>
          )
        }
<%_ if (paginationInfiniteScroll) { _%>
        </InfiniteScroll>
<%_ } _%>
      </div>
<%_ if (!databaseTypeCassandra) { _%>
  <%_ if (paginationPagination) { _%>
        { totalItems ? (<div className={ <%= entityInstance %>List && <%= entityInstance %>List.length > 0 ? '' : 'd-none' }>
          <div className="justify-content-center d-flex">
            <JhiItemCount
              page={paginationState.activePage}
              total={totalItems}
              itemsPerPage={paginationState.itemsPerPage}
              <% { if (enableTranslation) { %>i18nEnabled<% }} %>
            />
          </div>
          <div className="justify-content-center d-flex">
            <JhiPagination
              activePage={paginationState.activePage}
              onSelect={handlePagination}
              maxButtons={5}
              itemsPerPage={paginationState.itemsPerPage}
              totalItems={totalItems}
            />
          </div>
        </div>) : '' }
  <% } _%>
<%_ } _%>
    </div>
  );
};

export default <%= entityReactName %>;
